package com.abaaba.project2.controller;

import com.abaaba.project2.bean.Storage;
import com.abaaba.project2.bean.bo.StorageListBo;
import com.abaaba.project2.bean.vo.BaseRespVo;
import com.abaaba.project2.bean.vo.StorageListVo;
import com.abaaba.project2.service.AdminStorageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.UUID;

@RestController
@RequestMapping("/admin/storage")
public class AdminStorageController {

    @Autowired
    AdminStorageService adminStorageService;

    @RequestMapping("/list")
    public BaseRespVo storageList(StorageListBo storageListBo)
    {

        StorageListVo storageListVo = adminStorageService.getStorageList(storageListBo);

        return BaseRespVo.ok(storageListVo);

    }

    @RequestMapping("/create")
    public BaseRespVo storageCreate(@RequestParam("file") MultipartFile myfile) throws IOException {
        Date date = new Date(System.currentTimeMillis());

        Storage storage = new Storage();
        storage.setKey(UUID.randomUUID().toString()+myfile.getOriginalFilename().substring(myfile.getOriginalFilename().lastIndexOf(".")));
        storage.setAddTime(date);
        storage.setUpdateTime(date);
        storage.setDeleted(false);
        storage.setName(myfile.getOriginalFilename());
        storage.setSize((int) myfile.getSize());
        storage.setType(myfile.getContentType());
        storage.setUrl("http://localhost:8083/wx/storage/fetch/"+storage.getKey());

        String picPath = "D://project2/";
        String pic = picPath + storage.getKey();
        File file = new File(pic);
        myfile.transferTo(file);

        Integer id = adminStorageService.storageCreate(storage);

        storage.setId(id);



        return BaseRespVo.ok(storage);

    }

    @RequestMapping("/update")
    public BaseRespVo storageUpdate(@RequestBody Storage storage)
    {
        adminStorageService.storageUpdate(storage);

        return BaseRespVo.ok();
    }

    @RequestMapping("/delete")
    public BaseRespVo storageDelete(@RequestBody Storage storage)
    {
        adminStorageService.storageDelete(storage);

        return BaseRespVo.ok();
    }

}
